<?php

namespace app\controller\web;

use app\exception\ErrnoPlus;
use app\service\AccountService;
use share\service\UserBaseService;
use app\validate\PageValidate;
use app\validate\UserInfoValidate;
use share\exception\ApiException;
use share\service\UserDetailService;
use share\service\UserBindService;
use share\utils\Helper;

class UserInfoController extends WebBaseController{
    public function initValidate(){        
        $this->validate = new UserInfoValidate();
    }

    public function list_action(){
        $input = $this->check();
        $page = $this->check('pageInfo',null,(new PageValidate()));
        $data = AccountService::getListInfo($input,$page);   
        $userDetails = UserDetailService::getAll(array_column($data,'id'));
        $userBinds = UserBindService::getAllUserFormatBindInfo(array_column($data,'id'));
        $userList = [];
        foreach($data as $user){
            $uid = $user['id'];
            $detail = Helper::filterOne($userDetails,['id' => $uid]);
            $bind = isset($userBinds[$uid]) ? $userBinds[$uid] : UserBindService::defaultBindInfo();
            $tmp = array_merge($user,$detail,$bind);
            $userList[] = $tmp;
        }        
        $data = Helper::arrayListUnderscoreToCamelKey($userList);
        $total = AccountService::getListCountInfo($input);
        return self::ok(self::formatPageData($page,$total,$data));
    }

    public function edit_action(){
        $input = $this->check();
        AccountService::setUserLocation($input['userId'],$input['location']);
        return self::ok();
    }

    /**
     * 用户关联的设备信息
     */
    public function device_info_action(){
        $input = $this->check();
        $userId = $input['userId'];
        if(empty($userId)){
            throw  new ApiException("user id error",ErrnoPlus::PARAM_ERROR);
        }
        $deviceInfo = AccountService::getUserDeviceInfo($userId);
        return self::ok($deviceInfo);
    }

    public function data_board_action(){
        $input = $this->check();
        $vendor = $input['vendor'];
        $phoneRegisterTotal = UserBaseService::count([
            'vendor' => $vendor,
            'phone' => ['<>',''],
        ]);
        $emailRegisterTotal = UserBaseService::count([
            'vendor' => $vendor,
            'email' => ['<>',''],
        ]);

        //今日登录用户数  未实现
        $data['dayLogin'] = [];
        $data['registerTotal'] = [
            'email' => $emailRegisterTotal,
            'phone' => $phoneRegisterTotal,
        ];
        $data['dayRegister'] = AccountService::getTodayRegisterInfo($vendor);
        return self::ok($data);
    }

}